package cn.sh.ideal.yedis.util;

import cn.sh.ideal.yedis.core.RedisOperation;
@SuppressWarnings({"rawtypes"})
public class RedisLock {

	/** 加锁标志 */
	private static final String LOCKED = "TRUE";
	/** 默认超时时间（毫秒） */
	private static final long DEFAULT_TIME_OUT = 1000 * 180;

	private static final String SET_IF_NOT_EXIST ="NX";
	private static final String SET_WITH_EXPIRE_TIME ="PX";

	private String key;

	private RedisOperation operation;

	public RedisLock(String key,RedisOperation operation) {
		this.key = "lock_" + key;
		this.operation = operation;
	}
	
	/**
	 * 加锁 超时时间默认时间3分钟
	 * @return
	 */
	public boolean lock() {
		return lock(DEFAULT_TIME_OUT);
	}
	
	/**
	 * 加锁
	 * @param timeout 超时时间 单位毫秒
	 * @return
	 */
	public boolean lock(long timeout) {
		return operation.set(key, LOCKED, SET_IF_NOT_EXIST, timeout, SET_WITH_EXPIRE_TIME);
	}

	/**
	 * 解锁 无论是否加锁成功，都需要调用unlock 应该以： lock(); try { doSomething(); } finally { unlock()； } 的方式调用
	 */
	public void unlock() {
		try {
			this.operation.del(key);
		} finally {
		}
	}

	public String getKey() {
		return key;
	}

	public void setKey(String key) {
		this.key = key;
	}

}
